package com.caochenlei.table;

import java.util.HashSet;
import java.util.Set;

public class HashTable<Key, Value> {
    private int M;                              //哈希表的大小
    private int N;                              //键值对的对数
    private SymbolTable<Key, Value>[] table;    //存放链表对象的数组，这里采用无序符号表，也可以用红黑树

    public HashTable(int M) {
        this.M = M;
        table = new SymbolTable[M];
        for (int i = 0; i < M; i++) {
            table[i] = new SymbolTable<>();
        }
    }

    //获取哈希表键值个数
    public int size() {
        return N;
    }

    //判断哈希表是否为空
    public boolean isEmpty() {
        return N == 0;
    }

    //获取指定key哈希值
    private int hash(Key key) {
        return key.hashCode() & (table.length - 1);
    }

    //向哈希表中添加键值
    public void put(Key key, Value value) {
        table[hash(key)].put(key, value);
        N++;
    }

    //删除哈希表中的key
    public void delete(Key key) {
        table[hash(key)].delete(key);
        N--;
    }

    //获取key对应的value
    public Value get(Key key) {
        return table[hash(key)].get(key);
    }

    //获取哈希表中所有key的集合
    public Set<Key> keySet() {
        Set<Key> keySet = new HashSet<>();
        for (SymbolTable<Key, Value> keyValueSymbolTable : table) {
            keySet.addAll(keyValueSymbolTable.keySet());
        }
        return keySet;
    }

    //获取哈希表中所有value的集合
    public Set<Value> valueSet() {
        Set<Value> valueSet = new HashSet<>();
        for (SymbolTable<Key, Value> keyValueSymbolTable : table) {
            valueSet.addAll(keyValueSymbolTable.valueSet());
        }
        return valueSet;
    }
}
